<template>
  <div>
    <label>
      <span>
        <input v-if="group" v-model="model" type="radio" :disabled="disabled" :value="label" @change="change">
        <input v-else type="radio" :disabled="disabled" :value="currentValue" @change="change">
      </span>
      <slot></slot>
    </label>
  </div>
</template>

<script>
  import { findComponentUpward } from '../../utils/assist'
  import Emitter from '../../utils/emitter'
  export default {
    name: 'iRadio',
    mixins: [Emitter],
    components: {},
    props: {
      disabled: {
        type: Boolean,
        default: false
      },
      value: {
        type: [Boolean, Number, String],
        default: false
      },
      trueValue: {
        type: [Boolean, Number, String],
        default: true
      },
      falseValue: {
        type: [Boolean, Number, String],
        default: false
      },
      label: {
        type: [Boolean, Number, String]
      }
    },
    data () {
      return {
        currentValue: this.value,
        // 组合使用
        model: '',
        group: false,
        parent: null
      }
    },
    computed: {},
    watch: {
      value(val) {
        if (val === this.trueValue || val === this.falseValue) {
          this.updateModel()
        } else {
          throw new Error('Value should be trueValue or falseValue.')
        }
      }
    },
    mounted() {
      // 判断是不是radio-group
      this.parent = findComponentUpward(this, 'iRadioGroup')
      if (this.parent) {
        this.group = true
      }
      if (this.group) {
        this.parent.updateModel(true)
      } else {
        this.updateModel()
      }
    },
    methods: {
      change(event) {
        if (this.disabled) return false
        const checked = event.target.checked
        this.currentValue = checked
        const value = checked ? this.currentValue : this.falseValue
        this.$emit('input', value) // 通知父级修改，v-model的语法糖
        if (this.group) {
          this.parent.change(this.model)
        } else {
          this.$emit('on-change', value)
          this.dispatch('iFormItem', 'on-form-change', value) // 支持form表单的校验
        }
      },
      updateModel() {
        this.currentValue = this.value === this.trueValue
      }
    }
  }
</script>
<style lang='scss' scoped>
</style>
